from threading import Thread, Lock
import time
import cv2
from .cv_image import add_time_to_image,add_ultrasonic_servo_angle_to_image

from picamera2 import Picamera2

class CameraStream:
    OPENCV_NONE=0 
    OPENCV_OBJECT_FEATURE=1 
    
    def __init__(self, src=0):
        self.picam2 = Picamera2()
        self.picam2.configure(self.picam2.create_preview_configuration(main={"format": 'XRGB8888', "size": (640, 480)}))
        self.picam2.start()
        self.frame = self.picam2.capture_array()
        
        self.started = False
        self.read_lock = Lock()
        self.cur_opencv_action= CameraStream.OPENCV_NONE

    def start(self,ultrasonic_servo):
        if self.started:
            print("already started!!")
            return None
        self.started = True
        self.thread = Thread(target=self.update, args=(ultrasonic_servo,))
        self.daemon=True
        self.thread.start()
        return self

    def update(self,ultrasonic_servo):
        while self.started:
            time.sleep(0.1)
            frame = self.picam2.capture_array()
        
            #  import the opencv mothods to process the image from opencv_image 
            result=frame
            if self.cur_opencv_action==CameraStream.OPENCV_OBJECT_FEATURE:
               # add the time
                result=add_time_to_image(result)
                # add servo angle
                result=add_ultrasonic_servo_angle_to_image(result, ultrasonic_servo)

            self.read_lock.acquire()
            self.frame = result
            self.read_lock.release()

    def read(self):
        self.read_lock.acquire()
        frame = self.frame.copy()
        self.read_lock.release()
        return frame

    def stop(self):
        self.started = False
        self.thread.join()

    def __exit__(self, exc_type, exc_value, traceback):
        self.picam2.stop()
        